package com.ala4.oxcafe.boot.provider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

/**
 * @author PING
 * @date 2025/8/11 22:28
 */
@Slf4j
public class WeChatAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    public WeChatAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(WeChatAuthenticationToken.class, authentication,
                () -> this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                        "Only WeChatAuthenticationToken is supported"));

        String userPhoneNumber = authentication.getName();

        UserDetails userDetails = this.retrieveUser(userPhoneNumber);

        return createSuccessAuthentication(userPhoneNumber, userDetails);
    }

    protected Authentication createSuccessAuthentication(Object credentials, UserDetails userDetails) {
        // Ensure we return the original credentials the user supplied,
        // so subsequent attempts are successful even with encoded passwords.
        // Also ensure we return the original getDetails(), so that future
        // authentication events after cache expiry contain the details
        WeChatAuthenticationToken result = WeChatAuthenticationToken.authenticated(credentials, userDetails, userDetails.getAuthorities());
        log.debug("Authenticated user");
        return result;
    }

    /**
     * 获取用户信息-进行数据库的验证
     *
     * @param userPhoneNumber 微信用户手机号
     * @return
     * @throws AuthenticationException
     */
    protected final UserDetails retrieveUser(String userPhoneNumber)
            throws AuthenticationException {
        try {
            UserDetails loadedUser = this.userDetailsService.loadUserByUsername(userPhoneNumber);
            if (loadedUser == null) {
                throw new InternalAuthenticationServiceException(
                        "UserDetailsService returned null, which is an interface contract violation");
            }
            return loadedUser;
        } catch (UsernameNotFoundException ex) {
            throw ex;
        } catch (InternalAuthenticationServiceException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 被拦截到了之后会丢出一个未认证的token
        return WeChatAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
